home *** CD-ROM | disk | FTP | other *** search
/ Enter 2007 April / ENTER_CD_04_07.iso / Internet / WinHTTrack 3.23 / httrack-3.23.exe / {app} / src / htscache.c < prev    next >
Encoding:
C/C++ Source or Header  |  2003-01-23  |  29.6 KB  |  927 lines

  1. /* ------------------------------------------------------------ */
  2. /*
  3. HTTrack Website Copier, Offline Browser for Windows and Unix
  4. Copyright (C) Xavier Roche and other contributors
  5.  
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or any later version.
  10.  
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with this program; if not, write to the Free Software
  18. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  19.  
  20.  
  21. Important notes:
  22.  
  23. - We hereby ask people using this source NOT to use it in purpose of grabbing
  24. emails addresses, or collecting any other private information on persons.
  25. This would disgrace our work, and spoil the many hours we spent on it.
  26.  
  27.  
  28. Please visit our Website: http://www.httrack.com
  29. */
  30.  
  31.  
  32. /* ------------------------------------------------------------ */
  33. /* File: httrack.c subroutines:                                 */
  34. /*       cache system (index and stores files in cache)         */
  35. /* Author: Xavier Roche                                         */
  36. /* ------------------------------------------------------------ */
  37.  
  38. #include "htscache.h"
  39.  
  40. /* specific definitions */
  41. #include "htsbase.h"
  42. #include "htsbasenet.h"
  43. #include "htsmd5.h"
  44. #include <stdio.h>
  45. #include <stdlib.h>
  46. #include <string.h>
  47.  
  48. #include "htsnostatic.h"
  49. /* END specific definitions */
  50.  
  51. #undef test_flush
  52. #define test_flush if (opt->flush) { fflush(opt->log); fflush(opt->errlog); }
  53.  
  54. // routines de mise en cache
  55.  
  56. /*
  57.   VERSION 1.0 :
  58.   -----------
  59.  
  60. .ndx file
  61.  file with data
  62.    <string>(date/time) [ <string>(hostname+filename) (datfile_position_ascii) ] * number_of_links
  63.  file without data
  64.    <string>(date/time) [ <string>(hostname+filename) (-datfile_position_ascii) ] * number_of_links
  65.  
  66. .dat file
  67.  [ file ] * 
  68. with
  69.   file= (with data)
  70.    [ bytes ] * sizeof(htsblk header) [ bytes ] * n(length of file given in htsblk header)
  71.  file= (without data)
  72.    [ bytes ] * sizeof(htsblk header)
  73. with
  74.  <string>(name) = <length in ascii>+<lf>+<data>
  75.  
  76.  
  77.   VERSION 1.1/1.2 :
  78.   ---------------
  79.  
  80. .ndx file
  81.  file with data
  82.    <string>("CACHE-1.1") <string>(date/time) [ <string>(hostname+filename) (datfile_position_ascii) ] * number_of_links
  83.  file without data
  84.    <string>("CACHE-1.1") <string>(date/time) [ <string>(hostname+filename) (-datfile_position_ascii) ] * number_of_links
  85.  
  86. .dat file
  87.    <string>("CACHE-1.1") [ [Header_1.1] [bytes] * n(length of file given in header) ] *
  88. with
  89.  Header_1.1=
  90.    <int>(statuscode)
  91.    <int>(size)
  92.    <string>(msg)
  93.    <string>(contenttype)
  94.    <string>(last-modified)
  95.    <string>(Etag)
  96.    [<string>"SD" <string>(supplemental data)]
  97.    [<string>"SD" <string>(supplemental data)]
  98.    ...
  99.    <string>"HTS" (end of header)
  100.    <int>(number of bytes of data) (0 if no data written)
  101. */
  102.  
  103. // Nouveau: si != text/html ne stocke que la taille
  104.  
  105.  
  106. void cache_mayadd(httrackp* opt,cache_back* cache,htsblk* r,char* url_adr,char* url_fil,char* url_save) {
  107.   if ((opt->debug>0) && (opt->log!=NULL)) {
  108.     fspc(opt->log,"debug"); fprintf(opt->log,"File checked by cache: %s"LF,url_adr);
  109.   }            
  110.   // ---stockage en cache---
  111.   // stocker dans le cache?
  112.   if (opt->cache) {
  113.     if (cache->dat!=NULL) {
  114.       // c'est le seul endroit ou l'on ajoute des elements dans le cache (fichier entier ou header)
  115.       // on stocke tout fichier "ok", mais Θgalement les rΘponses 404,301,302...
  116.       if ((r->statuscode==200)         /* stocker rΘponse standard, plus */
  117.         || (r->statuscode==204)     /* no content */
  118.         || (r->statuscode==301)     /* moved perm */
  119.         || (r->statuscode==302)     /* moved temp */
  120.         || (r->statuscode==303)     /* moved temp */
  121.         || (r->statuscode==307)     /* moved temp */
  122.         || (r->statuscode==401)     /* authorization */
  123.         || (r->statuscode==403)     /* unauthorized */
  124.         || (r->statuscode==404)     /* not found */
  125.         || (r->statuscode==410)     /* gone */
  126.         )
  127.       {        /* ne pas stocker si la page gΘnΘrΘe est une erreur */
  128.         if (!r->is_file) {
  129.           // stocker fichiers (et robots.txt)
  130.           if ( (strnotempty(url_save)) || (strcmp(url_fil,"/robots.txt")==0)) {
  131.             // ajouter le fichier au cache
  132.             cache_add(*r,url_adr,url_fil,url_save,cache->ndx,cache->dat,opt->all_in_cache);
  133.           }
  134.         }
  135.       }
  136.     }
  137.   }
  138.   // ---fin stockage en cache---
  139. }
  140.  
  141.  
  142. /* Ajout d'un fichier en cache */
  143. void cache_add(htsblk r,char* url_adr,char* url_fil,char* url_save,FILE* cache_ndx,FILE* cache_dat,int all_in_cache) {
  144.   int pos;
  145.   char s[256];
  146.   char buff[HTS_URLMAXSIZE*4];
  147.   int ok=1;
  148.   int dataincache=0;    // donnΘe en cache?
  149.   /*char digest[32+2];*/
  150.   /*digest[0]='\0';*/
  151.  
  152.   // Longueur url_save==0?
  153.   if ( (strnotempty(url_save)==0) ) {
  154.     if (strcmp(url_fil,"/robots.txt")==0)        // robots.txt
  155.       dataincache=1;
  156.     else
  157.       return;   // erreur (sauf robots.txt)
  158.   }
  159.  
  160.   if (r.size <= 0)   // taille <= 0 
  161.     return;          // refusΘ..
  162.  
  163.   // Mettre les *donΘes* en cache ?
  164.   if (is_hypertext_mime(r.contenttype))    // html, mise en cache des donnΘes et 
  165.     dataincache=1;                               // pas uniquement de l'en tΩte
  166.   else if (all_in_cache)
  167.     dataincache=1;                               // forcer tout en cache
  168.  
  169.   /* calcul md5 ? */
  170.   /*
  171.   if (is_hypertext_mime(r.contenttype)) {    // html, calcul MD5
  172.     if (r.adr) {
  173.       domd5mem(r.adr,r.size,digest,1);
  174.     }
  175.   }*/
  176.  
  177.   // Position
  178.   fflush(cache_dat); fflush(cache_ndx);
  179.   pos=ftell(cache_dat);
  180.   // Θcrire pointeur seek, adresse, fichier
  181.   if (dataincache)   // patcher
  182.     sprintf(s,"%d\n",pos);    // ecrire tel que (eh oui Θvite les \0..)
  183.   else
  184.     sprintf(s,"%d\n",-pos);   // ecrire tel que (eh oui Θvite les \0..)
  185.  
  186.   // data
  187.   // Θcrire donnΘes en-tΩte, donnΘes fichier
  188.   /*if (!dataincache) {   // patcher
  189.     r.size=-r.size;  // nΘgatif
  190.   }*/
  191.  
  192.   // Construction header
  193.   ok=0;
  194.   if (cache_wint(cache_dat,r.statuscode)!=-1)       // statuscode
  195.   if (cache_wLLint(cache_dat,r.size)!=-1)           // size
  196.   if (cache_wstr(cache_dat,r.msg)!=-1)              // msg
  197.   if (cache_wstr(cache_dat,r.contenttype)!=-1)      // contenttype
  198.   if (cache_wstr(cache_dat,r.lastmodified)!=-1)     // last-modified
  199.   if (cache_wstr(cache_dat,r.etag)!=-1)             // Etag
  200.   if (cache_wstr(cache_dat,(r.location!=NULL)?r.location:"")!=-1)         // 'location' pour moved
  201.   if (cache_wstr(cache_dat,r.cdispo)!=-1)           // Content-disposition
  202.   if (cache_wstr(cache_dat,"HTS")!=-1)              // end of header
  203.     ok=1;       /* ok */
  204.   // Fin construction header
  205.  
  206.   /*if ((int) fwrite((char*) &r,1,sizeof(htsblk),cache_dat) == sizeof(htsblk)) {*/
  207.   if (ok) {
  208.     if (dataincache) {    // mise en cache?
  209.       if (!r.adr) {       /* taille nulle (parfois en cas de 301 */
  210.         if (cache_wLLint(cache_dat,0)==-1)          /* 0 bytes */
  211.           ok=0;
  212.       } else if (r.is_write==0) {  // en mΘmoire, recopie directe
  213.         if (cache_wLLint(cache_dat,r.size)!=-1) {
  214.           if (r.size>0) {   // taille>0
  215.             if (fwrite(r.adr,1,(INTsys)r.size,cache_dat)!=r.size)
  216.               ok=0;
  217.           } else    // taille=0, ne rien Θcrire
  218.             ok=0;
  219.         } else
  220.           ok=0;
  221.       } else {  // recopier fichier dans cache
  222.         FILE* fp;
  223.         // On recopie le fichier..
  224.         LLint file_size=fsize(fconv(url_save));
  225.         if (file_size>=0) {
  226.           if (cache_wLLint(cache_dat,file_size)!=-1) {
  227.             fp=fopen(fconv(url_save),"rb");
  228.             if (fp!=NULL) {
  229.               char buff[32768];
  230.               INTsys nl;
  231.               do {
  232.                 nl=fread(buff,1,32768,fp);
  233.                 if (nl>0) { 
  234.                   if ((INTsys)fwrite(buff,1,(INTsys)nl,cache_dat)!=nl) {  // erreur
  235.                     nl=-1;
  236.                     ok=0;
  237.                   }
  238.                 }
  239.               } while(nl>0);
  240.               fclose(fp);
  241.             } else ok=0;
  242.           } else ok=0;
  243.         } else ok=0;
  244.       }
  245.     } else {
  246.       if (cache_wLLint(cache_dat,0)==-1)          /* 0 bytes */
  247.         ok=0;
  248.     }
  249.   } else ok=0;
  250.   /*if (!dataincache) {   // dΘpatcher
  251.     r.size=-r.size;
  252.   }*/
  253.  
  254.   // index
  255.   // adresse+cr+fichier+cr
  256.   if (ok) {
  257.     buff[0]='\0'; strcatbuff(buff,url_adr); strcatbuff(buff,"\n"); strcatbuff(buff,url_fil); strcatbuff(buff,"\n");
  258.     cache_wstr(cache_ndx,buff);
  259.     fwrite(s,1,strlen(s),cache_ndx);
  260.   }  // si ok=0 on a peut Ωtre Θcrit des donnΘes pour rien mais on s'en tape
  261.   
  262.   // en cas de plantage, on aura au moins le cache!
  263.   fflush(cache_dat); fflush(cache_ndx);
  264. }
  265.  
  266.  
  267. // lecture d'un fichier dans le cache
  268. // si save==null alors test unqiquement
  269. htsblk cache_read(httrackp* opt,cache_back* cache,char* adr,char* fil,char* save,char* location) {
  270. #if HTS_FAST_CACHE
  271.   long int hash_pos;
  272.   int hash_pos_return;
  273. #else
  274.   char* a;
  275. #endif
  276.   char buff[HTS_URLMAXSIZE*2];
  277.   char location_default[HTS_URLMAXSIZE*2];
  278.   htsblk r;
  279.   int ok=0;
  280.   int header_only=0;
  281.  
  282.   memset(&r, 0, sizeof(htsblk)); r.soc=INVALID_SOCKET;
  283.   if (location) {
  284.     r.location = location;
  285.   } else {
  286.     r.location = location_default;
  287.   }
  288.   strcpybuff(r.location, ""); 
  289. #if HTS_FAST_CACHE
  290.   strcpybuff(buff,adr); strcatbuff(buff,fil);
  291.   hash_pos_return=inthash_read((inthash)cache->hashtable,buff,(long int*)&hash_pos);
  292. #else
  293.   buff[0]='\0'; strcatbuff(buff,"\n"); strcatbuff(buff,adr); strcatbuff(buff,"\n"); strcatbuff(buff,fil); strcatbuff(buff,"\n");
  294.   if (cache->use)
  295.     a=strstr(cache->use,buff);
  296.   else
  297.     a=NULL;       // forcer erreur
  298. #endif
  299.  
  300.   /* avoid errors on data entries */
  301.   if (adr[0] == '/' && adr[1] == '/' && adr[2] == '[') {
  302. #if HTS_FAST_CACHE
  303.     hash_pos_return = 0;
  304. #else
  305.     a = NULL;
  306. #endif
  307.   }
  308.  
  309.   // en cas de succΦs
  310. #if HTS_FAST_CACHE
  311.   if (hash_pos_return) {
  312. #else
  313.   if (a!=NULL) {  // OK existe en cache!
  314. #endif
  315.     INTsys pos;
  316. #if DEBUGCA
  317.     fprintf(stdout,"..cache: %s%s at ",adr,fil);
  318. #endif
  319.     
  320. #if HTS_FAST_CACHE
  321.     pos=hash_pos;     /* simply */
  322. #else
  323.     a+=strlen(buff);
  324.     sscanf(a,"%d",&pos);    // lire position
  325. #endif
  326. #if DEBUGCA
  327.     printf("%d\n",pos);
  328. #endif
  329.  
  330.     fflush(cache->olddat); 
  331.     if (fseek(cache->olddat,((pos>0)?pos:(-pos)),SEEK_SET) == 0) {
  332.       /* Importer cache1.0 */
  333.       if (cache->version==0) {
  334.         OLD_htsblk old_r;
  335.         if (fread((char*) &old_r,1,sizeof(old_r),cache->olddat)==sizeof(old_r)) { // lire tout (y compris statuscode etc)
  336.           r.statuscode=old_r.statuscode;
  337.           r.size=old_r.size;        // taille fichier
  338.           strcpybuff(r.msg,old_r.msg);
  339.           strcpybuff(r.contenttype,old_r.contenttype);
  340.           ok=1;     /* import  ok */
  341.         }
  342.       /* */
  343.       /* Cache 1.1 */
  344.       } else {
  345.         char check[256];
  346.         LLint size_read;
  347.         check[0]='\0';
  348.         //
  349.         cache_rint(cache->olddat,&r.statuscode);
  350.         cache_rLLint(cache->olddat,&r.size);
  351.         cache_rstr(cache->olddat,r.msg);
  352.         cache_rstr(cache->olddat,r.contenttype);
  353.         cache_rstr(cache->olddat,r.lastmodified);
  354.         cache_rstr(cache->olddat,r.etag);
  355.         cache_rstr(cache->olddat,r.location);
  356.         if (cache->version >= 2)
  357.           cache_rstr(cache->olddat,r.cdispo);
  358.         //
  359.         cache_rstr(cache->olddat,check);
  360.         if (strcmp(check,"HTS")==0) {           /* intΘgritΘ OK */
  361.           ok=1;
  362.         }
  363.         cache_rLLint(cache->olddat,&size_read);       /* lire size pour Ωtre s√r de la taille dΘclarΘe (rΘΘcrire) */
  364.         if (size_read>0) {                         /* si inscrite ici */
  365.           r.size=size_read;
  366.         } else {                              /* pas de donnΘes directement dans le cache, fichier prΘsent? */
  367.           if (r.statuscode!=200)
  368.             header_only=1;          /* que l'en tΩte ici! */
  369.         }
  370.       }
  371.  
  372.       /* Remplir certains champs */
  373.       r.totalsize=r.size;
  374.  
  375.       // lecture du header (y compris le statuscode)
  376.       /*if (fread((char*) &r,1,sizeof(htsblk),cache->olddat)==sizeof(htsblk)) { // lire tout (y compris statuscode etc)*/
  377.       if (ok) {
  378.         // sΘcuritΘ
  379.         r.adr=NULL;
  380.         r.out=NULL;
  381.         ////r.location=NULL;  non, fixΘe lors des 301 ou 302
  382.         r.fp=NULL;
  383.         
  384.         if ( (r.statuscode>=0) && (r.statuscode<=999)
  385.           && (r.notmodified>=0)  && (r.notmodified<=9) ) {   // petite vΘrif intΘgritΘ
  386.           if ((save) && (!header_only) ) {     /* ne pas lire uniquement header */
  387.             //int to_file=0;
  388.             
  389.             r.adr=NULL; r.soc=INVALID_SOCKET; 
  390.             // // r.location=NULL;
  391.             
  392. #if HTS_DIRECTDISK
  393.             // Court-circuit:
  394.             // Peut-on stocker le fichier directement sur disque?
  395.             if ((r.statuscode==200) && (!is_hypertext_mime(r.contenttype)) && (strnotempty(save))) {    // pas HTML, Θcrire sur disk directement
  396.               int ok=0;
  397.               
  398.               r.is_write=1;    // Θcrire
  399.               if (fexist(antislash(save))) {  // un fichier existe dΘja
  400.                 //if (fsize(antislash(save))==r.size) {  // mΩme taille -- NON tant pis (taille mal declaree)
  401.                 ok=1;    // plus rien α faire
  402.                 filenote(save,NULL);        // noter comme connu
  403.                 //}
  404.               }
  405.               
  406.               if ((pos<0) && (!ok)) { // Pas de donnΘe en cache et fichier introuvable : erreur!
  407.                 if (opt->norecatch) {
  408.                   filecreateempty(save);
  409.                   //
  410.                   r.statuscode=-1;
  411.                   strcpybuff(r.msg,"File deleted by user not recaught");
  412.                   ok=1;     // ne pas rΘcupΘrer (et pas d'erreur)
  413.                 } else {
  414.                   r.statuscode=-1;
  415.                   strcpybuff(r.msg,"Previous cache file not found");
  416.                   ok=1;    // ne pas rΘcupΘrer
  417.                 }
  418.               }
  419.               
  420.               if (!ok) {  
  421.                 r.out=filecreate(save);
  422. #if HDEBUG
  423.                 printf("direct-disk: %s\n",save);
  424. #endif
  425.                 if (r.out!=NULL) {
  426.                   char buff[32768+4];
  427.                   INTsys nl;
  428.                   LLint size;
  429.                   size=r.size;
  430.                   do {
  431.                     nl=fread(buff,1,(INTsys) minimum(size,32768),cache->olddat);
  432.                     if (nl>0) {
  433.                       size-=nl; 
  434.                       if ((INTsys)fwrite(buff,1,(INTsys)nl,r.out)!=nl) {  // erreur
  435.                         r.statuscode=-1;
  436.                         strcpybuff(r.msg,"Cache Read Error : Read To Disk");
  437.                       }
  438.                     }
  439.                   } while((nl>0) && (size>0) && (r.statuscode!=-1));
  440.                   
  441.                   fclose(r.out);
  442.                   r.out=NULL;
  443. #if HTS_WIN==0
  444.                   chmod(save,HTS_ACCESS_FILE);      
  445. #endif          
  446.                   usercommand(0,NULL,antislash(save));
  447.                 } else {
  448.                   r.statuscode=-1;
  449.                   strcpybuff(r.msg,"Cache Write Error : Unable to Create File");
  450.                   //printf("%s\n",save);
  451.                 }
  452.               }
  453.               
  454.             } else
  455. #endif
  456.             { // lire en mΘmoire
  457.               
  458.               if (pos<0) { // Pas de donnΘe en cache, bizarre car html!!!
  459.                 r.statuscode=-1;
  460.                 strcpybuff(r.msg,"Previous cache file not found (2)");
  461.               } else {
  462.                 // lire fichier (d'un coup)
  463.                 r.adr=(char*) malloct((INTsys)r.size+4);
  464.                 if (r.adr!=NULL) {
  465.                   if (fread(r.adr,1,(INTsys)r.size,cache->olddat)!=r.size) {  // erreur
  466.                     freet(r.adr);
  467.                     r.adr=NULL;
  468.                     r.statuscode=-1;
  469.                     strcpybuff(r.msg,"Cache Read Error : Read Data");
  470.                   } else
  471.                     *(r.adr+r.size)='\0';
  472.                   //printf(">%s status %d\n",back[p].r.contenttype,back[p].r.statuscode);
  473.                 } else {  // erreur
  474.                   r.statuscode=-1;
  475.                   strcpybuff(r.msg,"Cache Memory Error");
  476.                 }
  477.               }
  478.             }
  479.           }    // si save==null, ne rien charger (juste en tΩte)
  480.         } else {
  481. #if DEBUGCA
  482.           printf("Cache Read Error : Bad Data");
  483. #endif
  484.           r.statuscode=-1;
  485.           strcpybuff(r.msg,"Cache Read Error : Bad Data");
  486.         }
  487.       } else {  // erreur
  488. #if DEBUGCA
  489.         printf("Cache Read Error : Read Header");
  490. #endif
  491.         r.statuscode=-1;
  492.         strcpybuff(r.msg,"Cache Read Error : Read Header");
  493.       }
  494.     } else {
  495. #if DEBUGCA
  496.       printf("Cache Read Error : Seek Failed");
  497. #endif
  498.       r.statuscode=-1;
  499.       strcpybuff(r.msg,"Cache Read Error : Seek Failed");
  500.     }
  501.   } else {
  502. #if DEBUGCA
  503.     printf("File Cache Not Found");
  504. #endif
  505.     r.statuscode=-1;
  506.     strcpybuff(r.msg,"File Cache Entry Not Found");
  507.   }
  508.   if (!location) {   /* don't export internal buffer */
  509.     r.location = NULL;
  510.   }
  511.   return r;
  512. }
  513.  
  514. /* write (string1-string2)-data in cache */
  515. /* 0 if failed */
  516. int cache_writedata(FILE* cache_ndx,FILE* cache_dat,char* str1,char* str2,char* outbuff,int len) {
  517.   if (cache_dat) {
  518.     char buff[HTS_URLMAXSIZE*4];
  519.     char s[256];
  520.     int pos;
  521.     fflush(cache_dat); fflush(cache_ndx);
  522.     pos=ftell(cache_dat);
  523.     /* first write data */
  524.     if (cache_wint(cache_dat,len)!=-1) {       // length
  525.       if ((INTsys)fwrite(outbuff,1,(INTsys)len,cache_dat) == (INTsys) len) {   // data
  526.         /* then write index */
  527.         sprintf(s,"%d\n",pos);
  528.         buff[0]='\0'; strcatbuff(buff,str1); strcatbuff(buff,"\n"); strcatbuff(buff,str2); strcatbuff(buff,"\n");
  529.         cache_wstr(cache_ndx,buff);
  530.         if (fwrite(s,1,(INTsys)strlen(s),cache_ndx) == strlen(s)) {
  531.           fflush(cache_dat); fflush(cache_ndx);
  532.           return 1;
  533.         }
  534.       }
  535.     }
  536.   }
  537.   return 0;
  538. }
  539.  
  540. /* read the data corresponding to (string1-string2) in cache */
  541. /* 0 if failed */
  542. int cache_readdata(cache_back* cache,char* str1,char* str2,char** inbuff,int* inlen) {
  543. #if HTS_FAST_CACHE
  544.   if (cache->hashtable) {
  545.     char buff[HTS_URLMAXSIZE*4];
  546.     long int pos;
  547.     strcpybuff(buff,str1); strcatbuff(buff,str2);
  548.     if (inthash_read((inthash)cache->hashtable,buff,(long int*)&pos)) {
  549.       if (fseek(cache->olddat,((pos>0)?pos:(-pos)),SEEK_SET) == 0) {
  550.         INTsys len;
  551.         cache_rint(cache->olddat,&len);
  552.         if (len>0) {
  553.           char* mem_buff=(char*)malloct(len+4);    /* Plus byte 0 */
  554.           if (mem_buff) {
  555.             if ((INTsys)fread(mem_buff,1,len,cache->olddat)==len) { // lire tout (y compris statuscode etc)*/
  556.               *inbuff=mem_buff;
  557.               *inlen=len;
  558.               return 1;
  559.             } else
  560.               freet(mem_buff);
  561.           }
  562.         }
  563.       }
  564.     }
  565.   }
  566. #endif
  567.   *inbuff=NULL;
  568.   *inlen=0;
  569.   return 0;
  570. }
  571.  
  572. // renvoyer uniquement en tΩte, ou NULL si erreur
  573. htsblk* cache_header(httrackp* opt,cache_back* cache,char* adr,char* fil) {
  574.   htsblk* r;
  575.   NOSTATIC_RESERVE(r, htsblk, 1);
  576.   *r=cache_read(opt,cache,adr,fil,NULL,NULL);              // test uniquement
  577.   if (r->statuscode != -1)
  578.     return r;
  579.   else
  580.     return NULL;
  581. }
  582.  
  583.  
  584. // Initialisation du cache: crΘer nouveau, renomer ancien, charger..
  585. void cache_init(cache_back* cache,httrackp* opt) {
  586.   // ---
  587.   // utilisation du cache: renommer ancien Θventuel et charger index
  588.   if (opt->cache) {
  589. #if DEBUGCA
  590.     printf("cache init: ");
  591. #endif
  592.     if (!cache->ro) {
  593. #if HTS_WIN
  594.       mkdir(fconcat(opt->path_log,"hts-cache"));
  595. #else
  596.       mkdir(fconcat(opt->path_log,"hts-cache"),HTS_PROTECT_FOLDER);
  597. #endif
  598.       if ((fexist(fconcat(opt->path_log,"hts-cache/new.dat"))) && (fexist(fconcat(opt->path_log,"hts-cache/new.ndx")))) {  // il existe dΘja un cache prΘcΘdent.. renommer
  599. #if DEBUGCA
  600.         printf("work with former cache\n");
  601. #endif
  602.         if (fexist(fconcat(opt->path_log,"hts-cache/old.dat")))
  603.           remove(fconcat(opt->path_log,"hts-cache/old.dat"));
  604.         if (fexist(fconcat(opt->path_log,"hts-cache/old.ndx")))
  605.           remove(fconcat(opt->path_log,"hts-cache/old.ndx"));
  606.         
  607.         rename(fconcat(opt->path_log,"hts-cache/new.dat"),fconcat(opt->path_log,"hts-cache/old.dat"));
  608.         rename(fconcat(opt->path_log,"hts-cache/new.ndx"),fconcat(opt->path_log,"hts-cache/old.ndx"));
  609.       } else {  // un des deux (ou les deux) fichiers cache absents: effacer l'autre Θventuel
  610. #if DEBUGCA
  611.         printf("new cache\n");
  612. #endif
  613.         if (fexist(fconcat(opt->path_log,"hts-cache/new.dat")))
  614.           remove(fconcat(opt->path_log,"hts-cache/new.dat"));
  615.         if (fexist(fconcat(opt->path_log,"hts-cache/new.ndx")))
  616.           remove(fconcat(opt->path_log,"hts-cache/new.ndx"));
  617.       }
  618.     }
  619.     
  620.     // charger index cache prΘcΘdent
  621.     if (
  622.       (
  623.       !cache->ro &&
  624.       fsize(fconcat(opt->path_log,"hts-cache/old.dat")) >=0 && fsize(fconcat(opt->path_log,"hts-cache/old.ndx")) >0
  625.       )
  626.       ||
  627.       (
  628.       cache->ro &&
  629.       fsize(fconcat(opt->path_log,"hts-cache/new.dat")) >=0 && fsize(fconcat(opt->path_log,"hts-cache/new.ndx")) > 0
  630.       )
  631.       ) {
  632.       FILE* oldndx=NULL;
  633. #if DEBUGCA
  634.       printf("..load cache\n");
  635. #endif
  636.       if (!cache->ro) {
  637.         cache->olddat=fopen(fconcat(opt->path_log,"hts-cache/old.dat"),"rb");        
  638.         oldndx=fopen(fconcat(opt->path_log,"hts-cache/old.ndx"),"rb");        
  639.       } else {
  640.         cache->olddat=fopen(fconcat(opt->path_log,"hts-cache/new.dat"),"rb");        
  641.         oldndx=fopen(fconcat(opt->path_log,"hts-cache/new.ndx"),"rb");        
  642.       }
  643.       // les deux doivent Ωtre ouvrables
  644.       if ((cache->olddat==NULL) && (oldndx!=NULL)) {
  645.         fclose(oldndx);
  646.         oldndx=NULL;
  647.       }
  648.       if ((cache->olddat!=NULL) && (oldndx==NULL)) {
  649.         fclose(cache->olddat);
  650.         cache->olddat=NULL;
  651.       }
  652.       // lire index
  653.       if (oldndx!=NULL) {
  654.         int buffl;
  655.         fclose(oldndx); oldndx=NULL;
  656.         // lire ndx, et lastmodified
  657.         if (!cache->ro) {
  658.           buffl=fsize(fconcat(opt->path_log,"hts-cache/old.ndx"));
  659.           cache->use=readfile(fconcat(opt->path_log,"hts-cache/old.ndx"));
  660.         } else {
  661.           buffl=fsize(fconcat(opt->path_log,"hts-cache/new.ndx"));
  662.           cache->use=readfile(fconcat(opt->path_log,"hts-cache/new.ndx"));
  663.         }
  664.         if (cache->use!=NULL) {
  665.           char firstline[256];
  666.           char* a=cache->use;
  667.           a+=cache_brstr(a,firstline);
  668.           if (strncmp(firstline,"CACHE-",6)==0) {       // Nouvelle version du cache
  669.             if (strncmp(firstline,"CACHE-1.",8)==0) {      // Version 1.1x
  670.               cache->version=(int)(firstline[8]-'0');           // cache 1.x
  671.               if (cache->version <= 2) {
  672.                 a+=cache_brstr(a,firstline);
  673.                 strcpybuff(cache->lastmodified,firstline);
  674.               } else {
  675.                 if (opt->errlog) {
  676.                   fspc(opt->errlog,"error"); fprintf(opt->errlog,"Cache: version 1.%d not supported, ignoring current cache"LF,cache->version);
  677.                   fflush(opt->errlog);
  678.                 }
  679.                 fclose(cache->olddat);
  680.                 cache->olddat=NULL;
  681.                 freet(cache->use);
  682.                 cache->use=NULL;
  683.               }
  684.             } else {        // non supportΘ
  685.               if (opt->errlog) {
  686.                 fspc(opt->errlog,"error"); fprintf(opt->errlog,"Cache: %s not supported, ignoring current cache"LF,firstline);
  687.                 fflush(opt->errlog);
  688.               }
  689.               fclose(cache->olddat);
  690.               cache->olddat=NULL;
  691.               freet(cache->use);
  692.               cache->use=NULL;
  693.             }
  694.             /* */
  695.           } else {              // Vieille version du cache
  696.             /* */
  697.             if (opt->log) {
  698.               fspc(opt->log,"warning"); fprintf(opt->log,"Cache: importing old cache format"LF);
  699.               fflush(opt->log);
  700.             }
  701.             cache->version=0;        // cache 1.0
  702.             strcpybuff(cache->lastmodified,firstline); 
  703.           }
  704.           opt->is_update=1;        // signaler comme update
  705.           
  706.           /* Create hash table for the cache (MUCH FASTER!) */
  707. #if HTS_FAST_CACHE
  708.           if (cache->use) {
  709.             char line[HTS_URLMAXSIZE*2];
  710.             char linepos[256];
  711.             int  pos;
  712.             while ( (a!=NULL) && (a < (cache->use+buffl) ) ) {
  713.               a=strchr(a+1,'\n');     /* start of line */
  714.               if (a) {
  715.                 a++;
  716.                 /* read "host/file" */
  717.                 a+=binput(a,line,HTS_URLMAXSIZE);
  718.                 a+=binput(a,line+strlen(line),HTS_URLMAXSIZE);
  719.                 /* read position */
  720.                 a+=binput(a,linepos,200);
  721.                 sscanf(linepos,"%d",&pos);
  722.                 inthash_add((inthash)cache->hashtable,line,pos);
  723.               }
  724.             }
  725.             /* Not needed anymore! */
  726.             freet(cache->use);
  727.             cache->use=NULL;
  728.           }
  729. #endif
  730.         }
  731.       }
  732.       }  // taille cache>0
  733.       
  734. #if DEBUGCA
  735.       printf("..create cache\n");
  736. #endif
  737.       if (!cache->ro) {
  738.         // ouvrir caches actuels
  739.         cache->dat=fopen(fconcat(opt->path_log,"hts-cache/new.dat"),"wb");        
  740.         cache->ndx=fopen(fconcat(opt->path_log,"hts-cache/new.ndx"),"wb");        
  741.         // les deux doivent Ωtre ouvrables
  742.         if ((cache->dat==NULL) && (cache->ndx!=NULL)) {
  743.           fclose(cache->ndx);
  744.           cache->ndx=NULL;
  745.         }
  746.         if ((cache->dat!=NULL) && (cache->ndx==NULL)) {
  747.           fclose(cache->dat);
  748.           cache->dat=NULL;
  749.         }
  750.         
  751.         if (cache->ndx!=NULL) {
  752.           char s[256];
  753.           
  754.           cache_wstr(cache->dat,"CACHE-1.2");
  755.           fflush(cache->dat);
  756.           cache_wstr(cache->ndx,"CACHE-1.2");
  757.           fflush(cache->ndx);
  758.           //
  759.           time_gmt_rfc822(s);   // date et heure actuelle GMT pour If-Modified-Since..
  760.           cache_wstr(cache->ndx,s);        
  761.           fflush(cache->ndx);    // un petit fflush au cas o∙
  762.           
  763.           // supprimer old.lst
  764.           if (fexist(fconcat(opt->path_log,"hts-cache/old.lst")))
  765.             remove(fconcat(opt->path_log,"hts-cache/old.lst"));
  766.           // renommer
  767.           if (fexist(fconcat(opt->path_log,"hts-cache/new.lst")))
  768.             rename(fconcat(opt->path_log,"hts-cache/new.lst"),fconcat(opt->path_log,"hts-cache/old.lst"));
  769.           // ouvrir
  770.           cache->lst=fopen(fconcat(opt->path_log,"hts-cache/new.lst"),"wb");
  771.           {
  772.             filecreate_params tmp;
  773.             strcpybuff(tmp.path,opt->path_html);    // chemin
  774.             tmp.lst=cache->lst;                 // fichier lst
  775.             filenote("",&tmp);        // initialiser filecreate
  776.           }
  777.           
  778.           // supprimer old.txt
  779.           if (fexist(fconcat(opt->path_log,"hts-cache/old.txt")))
  780.             remove(fconcat(opt->path_log,"hts-cache/old.txt"));
  781.           // renommer
  782.           if (fexist(fconcat(opt->path_log,"hts-cache/new.txt")))
  783.             rename(fconcat(opt->path_log,"hts-cache/new.txt"),fconcat(opt->path_log,"hts-cache/old.txt"));
  784.           // ouvrir
  785.           cache->txt=fopen(fconcat(opt->path_log,"hts-cache/new.txt"),"wb");
  786.           if (cache->txt) {
  787.             fprintf(cache->txt,"date\tsize'/'remotesize\tflags(request:Update,Range state:File response:Modified,Chunked,gZipped)\t");
  788.             fprintf(cache->txt,"statuscode\tstatus ('servermsg')\tMIME\tEtag|Date\tURL\tlocalfile\t(from URL)"LF);
  789.           }
  790.           
  791.           // test
  792.           // cache_writedata(cache->ndx,cache->dat,"//[TEST]//","test1","TEST PIPO",9);
  793.         }
  794.         
  795.       } else {
  796.         cache->lst = cache->dat = cache->ndx = NULL;
  797.       }
  798.       
  799.   }
  800.   
  801. }
  802.  
  803.  
  804.  
  805.  
  806. // lire un fichier.. (compatible \0)
  807. char* readfile(char* fil) {
  808.   char* adr=NULL;
  809.   INTsys len=0;
  810.   len=fsize(fil);
  811.   if (len>0) {  // existe
  812.     FILE* fp;
  813.     fp=fopen(fconv(fil),"rb");
  814.     if (fp!=NULL) {  // n'existe pas (!)
  815.       adr=(char*) malloct(len+1);
  816.       if (adr!=NULL) {
  817.         if ((INTsys)fread(adr,1,len,fp)!=len) {    // fichier endommagΘ ?
  818.           freet(adr);
  819.           adr=NULL;
  820.         } else
  821.           *(adr+len)='\0';
  822.       }
  823.       fclose(fp);
  824.     }
  825.   }
  826.   return adr;
  827. }
  828.  
  829. char* readfile_or(char* fil,char* defaultdata) {
  830.   char* realfile=fil;
  831.   char* ret;
  832.   if (!fexist(fil))
  833.     realfile=fconcat(hts_rootdir(NULL),fil);
  834.   ret=readfile(realfile);
  835.   if (ret)
  836.     return ret;
  837.   else {
  838.     char *adr=malloct(strlen(defaultdata)+2);
  839.     if (adr) {
  840.       strcpybuff(adr,defaultdata);
  841.       return adr;
  842.     }
  843.   }
  844.   return NULL;
  845. }
  846.  
  847. // Θcriture/lecture d'une chaεne sur un fichier
  848. // -1 : erreur, sinon 0
  849. int cache_wstr(FILE* fp,char* s) {
  850.   INTsys i;
  851.   char buff[256+4];
  852.   i=strlen(s);
  853.   sprintf(buff,INTsysP "\n",i);
  854.   if (fwrite(buff,1,(INTsys)strlen(buff),fp) != strlen(buff))
  855.     return -1;
  856.   if (i>0)
  857.   if ((INTsys)fwrite(s,1,i,fp) != i)
  858.     return -1;
  859.   return 0;
  860. }
  861. void cache_rstr(FILE* fp,char* s) {
  862.   INTsys i;
  863.   char buff[256+4];
  864.   linput(fp,buff,256);
  865.   sscanf(buff,INTsysP,&i);
  866.   if (i < 0 || i > 32768)    /* error, something nasty happened */
  867.     i=0;
  868.   if (i>0)
  869.     fread(s,1,i,fp);
  870.   *(s+i)='\0';
  871. }
  872. int cache_brstr(char* adr,char* s) {
  873.   int i;
  874.   int off;
  875.   char buff[256+4];
  876.   off=binput(adr,buff,256);
  877.   adr+=off;
  878.   sscanf(buff,"%d",&i);
  879.   if (i>0)
  880.     strncpy(s,adr,i);
  881.   *(s+i)='\0';
  882.   off+=i;
  883.   return off;
  884. }
  885. int cache_quickbrstr(char* adr,char* s) {
  886.   int i;
  887.   int off;
  888.   char buff[256+4];
  889.   off=binput(adr,buff,256);
  890.   adr+=off;
  891.   sscanf(buff,"%d",&i);
  892.   if (i>0)
  893.     strncpy(s,adr,i);
  894.   *(s+i)='\0';
  895.   off+=i;
  896.   return off;
  897. }
  898. /* idem, mais en int */
  899. int cache_brint(char* adr,int* i) {
  900.   char s[256];
  901.   int r=cache_brstr(adr,s);
  902.   if (r!=-1)
  903.     sscanf(s,"%d",i);
  904.   return r;
  905. }
  906. void cache_rint(FILE* fp,int* i) {
  907.   char s[256];
  908.   cache_rstr(fp,s);
  909.   sscanf(s,"%d",i);
  910. }
  911. int cache_wint(FILE* fp,int i) {
  912.   char s[256];
  913.   sprintf(s,"%d",(int) i);
  914.   return cache_wstr(fp,s);
  915. }
  916. void cache_rLLint(FILE* fp,LLint* i) {
  917.   char s[256];
  918.   cache_rstr(fp,s);
  919.   sscanf(s,LLintP,i);
  920. }
  921. int cache_wLLint(FILE* fp,LLint i) {
  922.   char s[256];
  923.   sprintf(s,LLintP,(LLint) i);
  924.   return cache_wstr(fp,s);
  925. }
  926. // -- cache --
  927.